package org.kimoji.security.dao;

import java.util.Map;

import org.kimoji.base.BaseDAO;
import org.kimoji.entity.User;
import org.kimoji.security.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

@Repository
public class SecurityDAO extends BaseDAO{

	private static final String AUTH = "auth:";
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	public Account loadAccountByLoginName(String loginName) {
		Map<String,Object> params = generateParams();
		params.put("loginName", loginName);
		return sqlSession.selectOne("SecurityMapper.loadAccountByLoginName", params);
	}
	
	public User loadAccountById(int id) {
		Map<String,Object> params = generateParams();
		params.put("id", id);
		return sqlSession.selectOne("SecurityMapper.loadAccountById", params);
	}
	
	public Account saveAccount(Account account){
		Map<String,Object> params = generateParams();
		params.put("account", account);
		sqlSession.insert("SecurityMapper.saveAccount",params);
		return account;
	}
	
	public void cacheAuth(String key,String id){
		redisTemplate.opsForValue().set(AUTH + key, id);
	}
	
	public String loadAuth(String key){
		return (String)redisTemplate.opsForValue().get(AUTH + key);
	}
	
	public void eliminateAuth(String key){
		redisTemplate.delete(AUTH + key);
	}
	
}